<!-- 手工录入 -->
<template>
	<div class="outer-box">
		<div class="top_box">
			体检报告录入
		</div>
		<div class="content-box">
			<!-- 体检报告 -->
			<div class="content-left">
				<!-- <div class="line"></div> -->
				<div class="content-left-title">模板文件</div>
				<!-- pdf -->
				<div class="file-line"></div>
				<div class="content-report" v-loading="loading">
          <iframe ref="Iframe" class="prism-player" :src="pdfUrl" width="100%" height="100%"></iframe>
				</div>
				<!-- <div class="content-left-slide">
					<span class="slide-title">图片大小</span>
					<el-slider class="slider"
						show-input
						>
					</el-slider>
				</div> -->
				
			</div>
			<!-- 录入信息 -->
			<div class="content-right">
				<manualEntryInfo ref="manualEntryInfo" :baseInfo="baseInfo" :insuredInfo="insuredInfo" :appntInfo="appntInfo" :peInfo="peInfo" :pageDisabled="pageDisabled" @updateManualInfo="updateManualInfo"></manualEntryInfo>
				<!-- 提交AI核保 -->
				<el-button icon="el-icon-position" class="btm btm_1" title="提交AI核保" @click="savePage(1)" v-if="!pageDisabled"></el-button>
				<!-- 保存 -->
				<el-button icon="el-icon-receiving" v-if="!routeData.aiTask && !pageDisabled" class="btm btm_2" title="保存" @click="savePage(2)"></el-button>
				<!-- 返回 -->
				<el-button v-if="!routeData.aiTask" class="btm btm_3" title="返回" @click="goBack">
          <icon-svg style="font-size: 14px" iconClass="icon-callback"></icon-svg>
        </el-button>
			</div>
			<!-- <manualEntryCoom :isShow="isShow"></manualEntryCoom> -->
		</div>
	</div>
</template>

<script>
// import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
// import templateFile from "../../../components/robot/TemplateFile.vue";  //引入体检报告组件
// import manualEntryCoom from "../../../components/robot/manualEntryCoom.vue"  //弹出表格
import manualEntryInfo from "../../../components/robot/manualEntryInfo.vue"  //客户信息、体检信息公用组件
// import { AddPdf } from "../../../components/robot/AddPdf.vue"  //弹出表格
import constant from '@/utils/constant';
import {
	getClientInfo,
	getPEInfo,
	peInfoAction
} from"@/api/taskCenter/manualEntry"
import pageCall from "@/utils/pageCall";

export default {
	components: {
		// templateFile: templateFile,     //体检报告组件
		// manualEntryCoom,
    manualEntryInfo
	},
	data() {
		return {
      loading: false, //默认不显示loading
      pdfUrl: '',
			tiffSrc: '',
			routeData: {},
      pageDisabled: false,
      reqSuccess: false,  //查询接口是否请求成功
      saveFlag: false,  //保存接口是否请求成功
			"appntInfo": {
				"age": "",
				"birthday": "",
				"clientCode": "",
				"clientName": "",
				"clientSecuityno": "",
				"clientType": "",
				"healthMap": {
					'1': []},
				"isDrink": "",  // id
				"isFewDrink": "",  // id
				"isSmoke": "",  // id
				"maritalStatus": "",  // id
				"sex": "",  // id
				"smokingAmount": ""
			},
      baseInfo: {},  //基本信息-保单号、受理号
			"insuredInfo": {
				"age": "",
				"birthday": "",
				"clientCode": "",
				"clientName": "",
				"clientSecuityno": "",
				"clientType": "",
				"healthMap": {
					'1': []},
				"isDrink": "",  // id
				"isFewDrink": "",  // id
				"isSmoke": "",  // id
				"maritalStatus": "",  // id
				"sex": "",  // id
				"smokingAmount": ""
			},
			peInfo: {
				riskPEs: [],
				rulePEs:  [],
			},
      manualInfo: {}
		}
	},
  mounted(){},
  activated(){
    this.reqSuccess = false
    // 请求数据传递给右侧
    let manualEntryInfo = this.$route.path == '/home/taskCenter/manualEntry' ? sessionStorage.getItem('manualEntryInfo') : 
    this.$route.path == '/home/taskCenter/manualEntryView' ? sessionStorage.getItem('manualEntryViewInfo') : sessionStorage.getItem('manualRecord')
    if(manualEntryInfo) this.routeData = JSON.parse(manualEntryInfo)
    this.pageDisabled = this.$route.path == '/home/taskCenter/manualEntryView' ? true : false
    if(this.$store.state.loading.manualEntrySaveFlag) this.queryData();
    if(this.routeData.taskNo) {
      this.loading = true;
      let url = '/static/pdf/web/viewer.html'
      if(window.location.hostname == 'localhost') url = '/static/pdf/web/viewer.html'
      this.pdfUrl = url + "?file="+encodeURIComponent(`/ilmp-aus-main-app/nlp/getPdfByTaskNo?taskNo=${this.routeData.taskNo}`)

      const iframe = this.$refs.Iframe;
      // 兼容处理
      if (iframe.attachEvent) {
        // IE
        iframe.attachEvent("onload", () => {
          this.loading = false;
        });
      } else {
        // 非IE
        iframe.onload = () => {
          this.loading = false;
        };
      }
		}

    this.$refs.manualEntryInfo.activeName = 'first'
		this.$refs.manualEntryInfo.appntOrInsure = '2'
  },
	methods: {
		queryData() {
      this.reqSuccess = false
			this.show();
			let params = {
				itemId: this.routeData.itemId,
				mainId: this.routeData.mainId,
				peOrgCode: this.routeData.peOrgCode,
				itemStatus: this.routeData.itemStatus,
				peCode: this.routeData.peCode
			}
			const clientPromise = getClientInfo(params)
			const pePromise = getPEInfo(params)
			Promise.all([clientPromise, pePromise]).then(result => {
        // 基本信息
        this.baseInfo = {
          accepted: result[0].data.accepted,
          policy: result[0].data.policy
        }
        // ---客户信息
        // 后端数据格式查出是string，数据字典是int，不转换格式无法翻译
				result[0].data.appntInfo.sex = Number(result[0].data.appntInfo.sex)
				result[0].data.appntInfo.maritalStatus = Number(result[0].data.appntInfo.maritalStatus)
				result[0].data.insuredInfo.sex = Number(result[0].data.insuredInfo.sex)
				result[0].data.insuredInfo.maritalStatus = Number(result[0].data.insuredInfo.maritalStatus)
        if(result[0].data.appntInfo.clientType == '3') this.appntInfo = result[0].data.insuredInfo;
        else this.appntInfo = result[0].data.appntInfo;
				this.insuredInfo = result[0].data.insuredInfo;

        console.log(JSON.parse(JSON.stringify(this.appntInfo)),'查询接口返回的');
        // ---体检信息
        result[1].data.rulePEs.forEach(item => {
					item.childPEVos.forEach(child => {
						let unitId = '';
						let unitName = '';
						child.units.forEach(unit => {
							if(unit.isDefault === '1'){
								unitId = unit.unitId;
								unitName = unit.unitName;
							}
						})
						child.unitId = unitId;
						child.unitName = unitName;
					})
				})
				this.peInfo = result[1].data;
        this.manualInfo = {
          peInfo: this.peInfo,
          appntInfo: this.appntInfo,
          insuredInfo: this.insuredInfo,
        }
        this.$forceUpdate()
        setTimeout(()=>{
          this.$refs.manualEntryInfo.expanHandle()
        },0)
				this.cancle();
        this.reqSuccess = true
			}).catch(() => {
				this.cancle();
			})
		},
		show() {
			this.$store.dispatch('loading/CHANGE_LOADING', true);
		},
		cancle() {
			this.$store.dispatch('loading/CHANGE_LOADING', false)
		},
    updateManualInfo(healthMap,clientType,appntOrInsure){
      let manualInfo = JSON.parse(sessionStorage.getItem('manualInfo'))
      if(clientType == '3'){
        manualInfo.appntInfo.healthMap = healthMap
        manualInfo.insuredInfo.healthMap = healthMap
      }else if(appntOrInsure == '1') manualInfo.appntInfo.healthMap = healthMap
      else manualInfo.insuredInfo.healthMap = healthMap
      sessionStorage.setItem('manualInfo',JSON.stringify(manualInfo))
    },
		savePage(num,noBackFlag) {
      if(this.saveFlag) return
      let manualInfo = JSON.parse(sessionStorage.getItem('manualInfo'))
      if(num == 1){
        if(!this.$refs.manualEntryInfo.validateFlag()) {
          this.$message.warning('请选择既往史、家族史的疾病治疗状况')
          return
        }
        if(this.$refs.manualEntryInfo.childResultValidate() ) {
          this.$refs.manualEntryInfo.activeName = 'second'
          return
        }
      }
      // if(!this.$refs.manualEntryInfo.childResultValidate() ){
        if(!noBackFlag) this.show()
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        let userId = userInfo.account || '';
        // 组装数据
        let addRulePEVos = constant.deepClone(manualInfo.peInfo.rulePEs);
        addRulePEVos.forEach(item => {
          for(let i = item.childPEVos.length - 1; i >= 0; i--) {
            let child = item.childPEVos[i];
            if(child.childResult.trim() === '') {
              item.childPEVos.splice(i, 1);
            } else {
              delete child.units;
              delete child.unitId;
              let id = child?.threshold?.thresholdId;
              let thresholdStr = !id ? '' : child.threshold.type == '1' ? child.threshold.thresholdStart + '-' + child.threshold.thresholdEnd : child.threshold.thresholdStart
              child.threshold = thresholdStr
            }
          }
        })
        let addRiskPEVos = constant.deepClone(manualInfo.peInfo.riskPEs);
        addRiskPEVos.forEach(item => {
          item.riskChildPEVos.forEach(child => {
            for(let i = child.propertys.length - 1; i >= 0; i--) {
              let pro = child.propertys[i];
              if(pro.isInput != 1) {
                let propertyValueId = pro.propertyValue;
                let propertyValueName = '';
                let index = pro.values.findIndex(val => propertyValueId === val.propertyValueId);
                if(index > -1) {
                  propertyValueName = pro.values[index].propertyValueName;
                }
                delete pro.values;
                pro.value = {
                  propertyValueId, propertyValueName
                }
                if(propertyValueId === '' && propertyValueName === '') {
                  child.propertys.splice(i, 1);
                }
              } else {
                if(pro.propertyValue === '') {
                  child.propertys.splice(i, 1);
                }
              }
            }
          })
        })
        console.log(JSON.parse(JSON.stringify(manualInfo.appntInfo)),'保存接口');
        let query = {
          accepted: this.routeData.accepted,
          action: num,  // 1.核保 2.暂存
          addClientVo: {
            addAppntInfo: manualInfo.appntInfo,
            addInsuredInfo: manualInfo.insuredInfo,
            clientType: this.$refs.manualEntryInfo.appntOrInsure == '1' ? manualInfo.appntInfo.clientType : manualInfo.insuredInfo.clientType
          },
          addPeInfoVo: {
            addRiskPEVos: addRiskPEVos.filter(fItem=>fItem.riskChildPEVos && fItem.riskChildPEVos.length),
            addRulePEVos: addRulePEVos.filter(fItem=>fItem.childPEVos && fItem.childPEVos.length),
          },
          chdrNum: this.routeData.chdrNum,
          itemId: this.routeData.itemId,
          itemPeCode: this.routeData.peCode,
          itemTaskNo: this.routeData.taskNo,
          mainId: this.routeData.mainId,
          userId
        }
        this.saveFlag = true
        if(num == 2) this.$store.commit('loading/SET_MANUALENTRYSAVEFLAG', false);
        peInfoAction(query).then(res => {
          this.saveFlag = false
          this.$store.commit('loading/SET_MANUALENTRYSAVEFLAG', true);
          pageCall.$emit('queryEnterWork',!noBackFlag);
          if(!noBackFlag) {
            this.cancle();
            this.$message.success(num == 1 ? '提交成功' : '保存成功');
            if(num == 1){
              let activeTag = JSON.parse(sessionStorage.getItem('tagActive'));
              let pathArr = activeTag.map(mItem=>mItem.path)
              if(pathArr.indexOf(this.$route.path)>-1){
                activeTag.splice(pathArr.indexOf(this.$route.path),1)
                sessionStorage.setItem('tagActive',JSON.stringify(activeTag))
              }
            }
            this.goBack();
          }
        }).catch(() => {
          this.saveFlag = false
          this.cancle()
          this.$store.commit('loading/SET_MANUALENTRYSAVEFLAG', true);
        })
      // }
		},
		// 返回录入工作池页面
		goBack() {
			// this.$router.push('/home/taskCenter/robou/enterWorkPool')
			this.$router.go(-1);
		},
	},
	created() {
	},
  watch: {
    '$store.state.loading.manualEntrySaveFlag': {
      handler(newVal, oldVal) {
        if(this.$route.path == '/home/taskCenter/manualEntry' || this.$route.path == '/home/taskCenter/manualRecord' || this.$route.path == '/home/taskCenter/manualEntryView'){
          if(newVal) {
            this.queryData();
          }
        }
			},
			deep: true,
    },
    '$route': {
      handler(newVal, oldVal) {
        if(this.$store.state.loading.manualEntrySaveFlag && this.reqSuccess && (oldVal.path == '/home/taskCenter/manualEntry' || oldVal.path == '/home/taskCenter/manualRecord')) this.savePage(2,true)
      },
			deep: true,
    }
	},
}

</script>

<style lang="less" scoped>
	@commonPadding: 20px;
	@commonBorder: 1px solid #e3dddd;

	.outer-box {
		overflow-x: scroll;
		// height: calc(100vh - 220px);
	}
	
	.top_box {
    height: 50px;
    line-height: 50px;
    /* margin-left: 15px; */
		padding-left: @commonPadding;
    border-bottom: @commonBorder;
		font-size: 16px;
		font-weight: 700;
		margin-bottom: 20px;
	}

	.content-box {
		// overflow-x: scroll;
    display: flex;
		position: relative;
		padding-left: @commonPadding;
		padding-right: @commonPadding;
		margin-bottom: 20px;
		.content-left {
			/* margin-right: 10px;
			padding-top: 50px;
			border: @commonBorder;
			border-width: 2px 3px 4px 3px;
			box-shadow: 2px 4px 2px #e3dddd; */
			.line, .file-line {
				border-bottom: @commonBorder;
			}
			.content-left-title {
				/* background-color: pink; */
				/* height: 4px; */
				/* line-height: 4px; */
				/* border-bottom: 1px solid #e3dddd; */
				margin: 10px 5px 10px;
				/* margin-bottom: 20px; */
				padding-left: 8px;
				border-left: 4px solid #f76767;
			}
			.content-report {
				margin: 20px 0 0;
				width: 540px;
        height: calc(100vh - 350px);
        min-height: 564px;
				// border: 1px dashed #0a66e6;
			}
			.content-left-slide {
				// display: flex;
				// justify-content: space-around;
				// align-content: center;
				color: #666;
				width: 100%;
				height: 50px;
				line-height: 50px;
				.slide-title {
					display: inline-block;
					width: 150px;
					text-align: right;
					font-size: 12px;
				}
				.slider {
					float: right;
					height: 100%;
					margin: 6px 20px 0 0;
					width: 340px;
				}
			}
		}
    .content-right {
			min-width: 700px;
			// background-color: pink;
			position: absolute;
			top: 0;
			left: 584px;
			right: 0;
    }
	}
	.btm {
		background-color: rgba(14, 12, 12, 0.374);
    position: absolute;
    right: 45px;
    border: 0px;
    color: #fff;
    line-height: 30px;
    font-size: 20px;
	}

	.btm_1 {
    top: 410px;
	}
	

	.btm_2 {
    top: 460px;
	}

	.btm_3 {
    top: 510px;
	}
	
</style>